<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="计划编码" prop="planCode">
        <el-input
          v-model="queryParams.planCode"
          placeholder="请输入计划编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="职业名称" prop="professionName">
        <el-input
          v-model="queryParams.professionName"
          placeholder="请输入职业名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="评价方式" prop="evaluationMethod">
        <el-select
          v-model="queryParams.evaluationMethod"
          placeholder="请选择评价方式"
          clearable
          class="!w-240px"
        >
          <el-option label="认定评价" value="assessment" />
          <el-option label="考试评价" value="examination" />
          <el-option label="混合评价" value="mixed" />
        </el-select>
      </el-form-item>
      <el-form-item label="计划状态" prop="planStatus">
        <el-select
          v-model="queryParams.planStatus"
          placeholder="请选择计划状态"
          clearable
          class="!w-240px"
        >
          <el-option label="草稿" :value="0" />
          <el-option label="已提交" :value="1" />
          <el-option label="已审批" :value="2" />
          <el-option label="已发布" :value="3" />
          <el-option label="进行中" :value="4" />
          <el-option label="已完成" :value="5" />
          <el-option label="已取消" :value="6" />
        </el-select>
      </el-form-item>
      <el-form-item label="评价模板" prop="templateId">
        <el-select
          v-model="queryParams.templateId"
          placeholder="请选择评价模板"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="template in templateList"
            :key="template.id"
            :label="template.templateName"
            :value="template.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:plan:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:plan:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划编码" align="center" prop="planCode" width="120" />
      <el-table-column label="计划名称" align="center" prop="planName" width="200" />
      <el-table-column label="职业名称" align="center" prop="professionName" width="150" />
      <el-table-column label="适用等级" align="center" prop="applicableLevels" width="120" />
      <el-table-column label="考评员" align="center" prop="kpyrName" width="200">
        <template #default="scope">
          <el-tooltip v-if="scope.row.kpyrName" :content="scope.row.kpyrName" placement="top">
            <span>{{ getDisplayEvaluators(scope.row.kpyrName) }}</span>
          </el-tooltip>
          <span v-else class="text-gray-400">未分配</span>
        </template>
      </el-table-column>
      <el-table-column label="评价方式" align="center" prop="evaluationMethod" width="100">
        <template #default="scope">
          {{ getEvaluationMethodText(scope.row.evaluationMethod) }}
        </template>
      </el-table-column>
      <el-table-column label="报名时间" align="center" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.registrationStartDate) }} ~ {{ formatDate(scope.row.registrationEndDate) }}
        </template>
      </el-table-column>
      <el-table-column label="评价时间" align="center" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.evaluationStartDate) }} ~ {{ formatDate(scope.row.evaluationEndDate) }}
        </template>
      </el-table-column>
      <el-table-column label="最大人数" align="center" prop="maxPeoplePerPlan" width="80" />
      <el-table-column label="计划状态" align="center" prop="planStatus" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.planStatus)">
            {{ getStatusText(scope.row.planStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:plan:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:plan:update']"
            v-if="scope.row.planStatus <= 1"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="workflow" v-if="scope.row.planStatus < 5">
                  状态管理
                </el-dropdown-item>
                <el-dropdown-item command="statistics">
                  统计信息
                </el-dropdown-item>
                <el-dropdown-item command="delete" v-if="scope.row.planStatus === 0">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PlanForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <PlanDetail ref="detailRef" />
  
  <!-- 工作流弹窗 -->
  <PlanWorkflow ref="workflowRef" @success="getList" />
  
  <!-- 统计信息弹窗 -->
  <PlanStatistics ref="statisticsRef" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { EvalPlanVO, EvalPlanPageReqVO, getPlanPage, deletePlan, exportPlan } from '@/api/eval'
import { getPublishedTemplateList } from '@/api/eval/template'
import download from '@/utils/download'
import PlanForm from './PlanForm.vue'
import PlanDetail from './PlanDetail.vue'
import PlanWorkflow from './PlanWorkflow.vue'
import PlanStatistics from './PlanStatistics.vue'

/** 评价计划 列表 */
defineOptions({ name: 'EvalPlan' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalPlanVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const templateList = ref<any[]>([]) // 模板列表
const queryParams = reactive<EvalPlanPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  planCode: undefined,
  planName: undefined,
  professionName: undefined,
  evaluationMethod: undefined,
  templateId: undefined,
  planStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getPlanPage(queryParams)
    console.log('获取到的计划列表数据:', data)
    console.log('第一条数据详情:', data.list[0])
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open('detail', id)
}

/** 工作流操作 */
const workflowRef = ref()
const openWorkflow = (row: EvalPlanVO) => {
  workflowRef.value.open(row)
}

/** 统计信息操作 */
const statisticsRef = ref()
const openStatistics = (id: number) => {
  statisticsRef.value.open(id)
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalPlanVO) => {
  switch (command) {
    case 'workflow':
      openWorkflow(row)
      break
    case 'statistics':
      openStatistics(row.id!)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deletePlan(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportPlan(queryParams)
    download.excel(data, '评价计划.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}



/** 获取状态文本 */
const getStatusText = (status: number) => {
  const textMap = {
    0: '草稿',
    1: '已提交',
    2: '已审批',
    3: '已发布',
    4: '进行中',
    5: '已完成',
    6: '已取消'
  }
  return textMap[status] || '未知'
}

/** 获取评价方式文本 */
const getEvaluationMethodText = (method: string) => {
  const textMap = {
    'assessment': '考核评价',
    'competency': '岗位能力评价',
    'combined': '考评结合',
    'competition': '竞赛认定'
  }
  return textMap[method] || method
}

/** 获取显示的考评员名称（限制显示长度） */
const getDisplayEvaluators = (evaluators: string) => {
  if (!evaluators) return ''
  const names = evaluators.split(',')
  if (names.length <= 2) {
    return evaluators
  }
  return `${names.slice(0, 2).join(',')}等${names.length}人`
}

/** 获取状态标签类型 */
const getStatusTagType = (status: number) => {
  const typeMap = {
    0: 'info',       // 草稿 - 信息
    1: 'warning',    // 已提交 - 警告
    2: 'primary',    // 已审批 - 主要
    3: 'success',    // 已发布 - 成功
    4: 'success',    // 进行中 - 成功
    5: 'success',    // 已完成 - 成功
    6: 'danger'      // 已取消 - 危险
  }
  return typeMap[status] || 'info'
}

/** 加载已发布的评价模板列表 */
const loadTemplateList = async () => {
  try {
    const result = await getPublishedTemplateList()
    templateList.value = Array.isArray(result) ? result : (result.data || [])
  } catch (error) {
    console.error('加载评价模板列表失败:', error)
    templateList.value = []
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  loadTemplateList()
})
</script>
